﻿@using Plotly.Blazor.LayoutLib
@using Plotly.Blazor.LayoutLib.YAxisLib
@using Plotly.Blazor.Traces.ScatterLib
@using System.Diagnostics
<PlotlyChart Id="TestId" Config="config" Layout="layout" Data="data" @ref="chart"/>

<div class="text-right">
    <button type="button" class="btn btn-primary" @onclick="() => Clear()">Clear</button>
    <button type="button" class="btn btn-primary" @onclick="() => AddData()">Add data</button>
</div>

@code
{
    PlotlyChart chart;

    Config config = new Config
    {
        Responsive = true
    };

    Layout layout = new Layout
    {
        Title = new Title
        {
            Text = "Multiple Axes"
        },
        YAxis = new List<YAxis>
        {
            new YAxis
            {
                Title = new LayoutLib.YAxisLib.Title
                {
                    Text = "Scatter Unit"
                }
            },
            new YAxis
            {
                Title = new LayoutLib.YAxisLib.Title
                {
                    Text = "Bar Unit"
                },
                Overlaying = "y",
                Side = SideEnum.Right
            }
        },
        Height = 500
    };

    List<ITrace> data = new List<ITrace>
    {
        new Scatter
        {
            Name = "ScatterTrace",
            Mode = ModeFlag.Lines | ModeFlag.Markers,
            X = new List<object>(),
            Y = new List<object>()
        },
        new Bar
        {
            Name = "BarTrace",
            YAxis = "y2",
            X = new List<object>(),
            Y = new List<object>(),
            Opacity = new decimal(0.7)
        }
    };

    private async Task AddData(int count = 100)
    {
        if (!(chart.Data.ElementAt(0) is Scatter scatter)) return;
        if (!(chart.Data.ElementAt(1) is Bar bar)) return;

        var (x, y) = Helper.GenerateData(scatter.X.Count + 1, scatter.X.Count + 1 + count);
        var (x2, y2) = Helper.GenerateData(bar.X.Count + 1, bar.X.Count + 1 + count, GenerateMethod.Cos);

        scatter.X.AddRange(x);
        scatter.Y.AddRange(y);

        bar.X.AddRange(x2);
        bar.Y.AddRange(y2);

        var stopwatch = new Stopwatch();
        stopwatch.Start();
        await chart.React();
        stopwatch.Stop();
        Console.WriteLine($"[PERF.] Update took {stopwatch.ElapsedMilliseconds}");
    }

    private async Task Clear()
    {
        if (!(chart.Data.ElementAt(0) is Scatter plot)) return;
        if (!(chart.Data.ElementAt(1) is Bar plot2)) return;

        plot.X.Clear();
        plot.Y.Clear();

        plot2.X.Clear();
        plot2.Y.Clear();

        await chart.React();
    }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await AddData();
        }
    }
}